# encoding=utf8

import requests
import itchat
import logging
import time

class Tuling:
    # 图灵人工智能回复
    @classmethod
    def response_text(self, text, user):
        key = u"cc6b9860fe5a464892c9538b2347254d"
        url = u"http://openapi.tuling123.com/openapi/api/v2"

        payload = u"{\n    \"perception\": {\n        \"inputText\": {\n            \"text\": \"%s\"\n        },\n      \"selfInfo\": {\n            \"location\": {\n                \"city\": \"重庆\",\n                \"province\": \"重庆\"\n            }\n        }\n    },\n    \"userInfo\": {\n        \"apiKey\": \"%s\",\n        \"userId\": \"%s\"\n    }\n}" % (text,key,'ss')
        headers = {
            'Content-Type': "application/json",
        }

        try:
            response = requests.request("POST", url, data=payload.encode('utf-8'), headers=headers)

            return response.json()['results']
        except:
            return

    # 根据图灵的回复定制微信回复
    @classmethod
    def response_wx(self, json, person):
        if (len(json) == 1) & (json[0]['resultType'] == 'text'):
            itchat.send(u'[小超]: %s' % json[0]['values']['text'],person)
        else:
            # 设置logging模块, 用中文的fileHandle
            handler = logging.FileHandler(
                './log/response-{}.log'.format(time.strftime('%Y-%m-%d', time.localtime(time.time()))
                                               ), mode='a', encoding='utf-8')
            logging.basicConfig(level=logging.ERROR,
                                format='%(asctime)s %(levelname)-8s: %(message)s',
                                handlers=[handler])

            logging.error(u'{}'.format(json))

